/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.connector.base.codec;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.je.connector.base.protocol.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;

/**
 * Packet解码器
 *
 * @ProjectName: instant-message
 * @Package: com.connector.base.codec
 * @ClassName: PacketDecoder
 * @Description: 定义Packet解码器
 * @Author: LIULJ
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2018</p>
 */
public final class PacketDecoder extends ByteToMessageDecoder {

    private static final Logger logger = LoggerFactory.getLogger(PacketDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() >= Packet.HEADER_LEN) {
            //1.记录当前读取位置位置.如果读取到非完整的frame,要恢复到该位置,便于下次读取
            in.markReaderIndex();
            Packet packet = decodeFrame(in);
            if (packet != null) {
                out.add(packet);
            } else {
                in.resetReaderIndex();
            }
        }
    }

    public Packet decodeFrame(ByteBuf in) {
        int readableBytes = in.readableBytes();
        int bodyLength = in.readInt();
        if (readableBytes < (bodyLength + Packet.HEADER_LEN)) {
            return null;
        }
        Packet packet = new Packet();
        Packet.decodePacket(packet, in, bodyLength);
        return packet;
    }

    public static Packet decodeFrame(String frame) {
        if (frame == null) {
            return null;
        }
        JSONObject jsonObject;
        try {
            jsonObject = JSONObject.parseObject(frame);
            Packet packet = new Packet(jsonObject.getByte("cmd"), jsonObject.getByte("type"));
            Integer sessionId = jsonObject.containsKey("sessionId") ? jsonObject.getInteger("sessionId") : null;
            if (sessionId != null) {
                packet.setSessionId(sessionId);
            }

            String body = jsonObject.containsKey("body") ? jsonObject.getString("body") : null;
            if (!Strings.isNullOrEmpty(body)) {
                byte[] bytes = body.getBytes(Charsets.UTF_8);
                packet.setBody(bytes);
                packet.setBodyLength(bytes.length);
            }
            return packet;
        } catch (Exception e) {
            logger.error("解析返回packet对象出现异常:[" + frame + "],不再执行往下执行", e);
            return null;
        }
    }

}
